package com.example.service.impl;

import com.example.mapper.GoodsCateMapper;
import com.example.pojo.GoodsCate;
import com.example.service.GoodsCateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@Service
public class GoodsCateServiceImpl implements GoodsCateService {

    @Autowired
    private GoodsCateMapper goodsCateMapper;

    // 新增商品分类
    @Override
    public void add(GoodsCate goodsCate) {
        // 自动填补最小空缺ID
        Integer gapId = goodsCateMapper.findFirstGapId();
        if (gapId == null) {
            gapId = Optional.ofNullable(goodsCateMapper.findMaxId()).orElse(0) + 1;
        }
        goodsCate.setId(gapId);

        // 补充属性值
        goodsCate.setCreateTime(LocalDateTime.now());
        goodsCate.setUpdateTime(LocalDateTime.now());

        // 如果图片URL为空，设置为null（避免数据库存储空字符串）
        if (goodsCate.getCatePic() != null && goodsCate.getCatePic().isEmpty()) {
            goodsCate.setCatePic(null);
        }

        goodsCateMapper.add(goodsCate);
    }

    // 查询所有商品分类列表
    @Override
    public List<GoodsCate> list() {
        return goodsCateMapper.list();
    }

    // 查看分类详情
    @Override
    public GoodsCate findById(Integer id) {
        return goodsCateMapper.findById(id);
    }

    // 更新商品分类
    @Override
    public void update(GoodsCate goodsCate) {
        // 获取原有分类信息
        GoodsCate existingCate = goodsCateMapper.findById(goodsCate.getId());
        if (existingCate == null) {
            throw new RuntimeException("分类不存在");
        }

        // 如果新图片URL为空，保持原有图片
        if (goodsCate.getCatePic() == null || goodsCate.getCatePic().isEmpty()) {
            goodsCate.setCatePic(existingCate.getCatePic());
        }

        // 更新修改时间
        goodsCate.setUpdateTime(LocalDateTime.now());

        goodsCateMapper.update(goodsCate);
    }

    // 删除商品分类
    @Override
    public void delete(Integer id) {
        // 先查询分类是否存在（避免无效操作）
        GoodsCate goodsCate = goodsCateMapper.findById(id);
        if (goodsCate == null) {
            throw new RuntimeException("分类不存在或已被删除");
        }

        // 执行删除
        goodsCateMapper.delete(id);
    }
}